package com.anxin.act.task.complete;

import com.anxin.act.task.service.ActTaskService;
import com.anxin.act.task.service.JumpTaskService;
import com.anxin.act.task.vo.FormPropertyVo;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 提交任务
 * @author: liuxiangyu
 * @date: 2020/4/26 16:21
 */
@Service
public class TaskComplete {
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected ActTaskService actTaskService;


    /**
     * 提交流程(该方法被子类覆盖)
     * @param taskVo 待办提交对象
     * @return 任务ID
     */
    public String complete(TaskVo taskVo){

        return taskVo.getId();
    }

    /**
     * 提交代办任务
     * @param taskVo
     */
    public void completeTask(TaskVo taskVo){
        ActUtils.setAssignee(taskVo.getTaskId(), UserUtils.getUserName());
        taskService.complete(taskVo.getTaskId(),taskVo.getOpinions());

    }

    /**
     * 设置任务变量
     * @param taskId
     * @param var
     */
    public void setTaskVariables(String taskId, Map<String,Object> var){
        taskService.setVariablesLocal(taskId,var);
    }

    /**
     * 发送提醒
     * @param task
     * @param proIns
     * @param comment
     */
    public void sendRemind(Task task, ProcessInstance proIns, String comment){

    }

    /**
     * 保存审批意见
     * @param taskVo
     */
    public void addCommentByFiled(TaskVo taskVo){
        List<FormPropertyVo> formFiledList = taskVo.getFormFieldList();
        for (int i = formFiledList.size(); i >0 ; i--) {
            FormPropertyVo formPropertyVo = formFiledList.get(i-1);
            StringBuffer comment = new StringBuffer(formPropertyVo.getName()+":"+(StringUtils.isNotBlank(formPropertyVo.getValueText())?formPropertyVo.getValueText():"无"));
            taskService.addComment(taskVo.getTaskId(), taskVo.getActId(), comment.toString());
        }
    }

    /**
     * 设置审批意见
     * @param taskVo
     */
    public void addComment(TaskVo taskVo){
        SysUser user = UserUtils.getUser();
        if(!user.getUserName().equals(taskVo.getViewRuTask().getAssignee())) {
            taskService.addComment(taskVo.getTaskId(), taskVo.getActId(),"委托处理人:" + user.getNickName());
        }

        this.addCommentByFiled(taskVo);

    }

    /**
     * 添加审批意见
     * @param taskVo
     * @param comment
     */
    public void addComment(TaskVo taskVo,String comment){
        taskService.addComment(taskVo.getTaskId(), taskVo.getActId(), comment);
    }




}
